package com.app.couponsharelife.data.remote

import androidx.lifecycle.LiveData
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.Contacts.APP_LIFE_IMGURL
import com.app.couponsharelife.manage.Contacts.RETURN_RATIO
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.jsoup.Jsoup
import java.io.File
import java.lang.StringBuilder
import java.math.BigDecimal
import java.text.DecimalFormat

/**
 * Created by guluwa on 2018/1/12.
 */

class RemoteDataSource {

    object SingletonHolder {
        //单例（静态内部类）
        val instance = RemoteDataSource()
    }

    companion object {

        fun getInstance() = SingletonHolder.instance
    }

    /**
     * 首页接口(新)
     */
    fun loadHomePage(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<HomePageBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.loadHomePage(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            val part2 = arrayListOf<HomePageBean.PictureBean>()
                            val images2 = arrayListOf<String>()
                            val part3 = arrayListOf<HomePageBean.PictureBean>()
                            val types = arrayListOf<HomePageBean.TypeBean>()
                            val part4 = arrayListOf<HomePageBean.PictureBean>()
                            val part5 = arrayListOf<HomePageBean.PictureBean>()
                            val images5 = arrayListOf<String>()
                            var selectedGoods: HomePageBean.GoodsLibraryBean? = null
                            val commissionRatio=DataUtils().getCommissionRatio()
                            for (item in it.data!!.list.picture) {
                                when (item.cate) {
                                    "2" -> {
                                        part2.add(item)
                                        images2.add(Contacts.BASEURL + item.thumb)
                                    }
                                    "3" -> part3.add(item)
                                    "4" -> part4.add(item)
                                    "5" -> {
                                        part5.add(item)
                                        images5.add(Contacts.BASEURL + item.thumb)
                                    }
                                    "9" -> it.data?.todayCheap = item
                                }
                            }
                            val count = part3.size / 2
                            val extra = part3.size % 2
                            for (i in 0 until part3.size / 2) {
                                if (i + count + extra < part3.size)
                                    types.add(HomePageBean.TypeBean(part3[i], part3[i + count + extra]))
                                else
                                    types.add(HomePageBean.TypeBean(part3[i], null))
                            }
                            for (item in it.data!!.list.goodsLibrary) {
                                for (good in item.goods.results.uatm_tbk_item) {
                                    good.commission_rate = good.tk_rate
                                    good.coupon_share_url = good.coupon_click_url
                                    good.url = good.click_url
                                    if (good.coupon_info != "") {
                                        good.has_coupon = true
                                        val start = good.coupon_info.indexOf("减")
                                        val str = good.coupon_info.substring(start + 1)
                                        val end = str.indexOf("元")
                                        good.coupon_price = str.substring(0, end)
                                        val couponFinalPrice = BigDecimal(good.zk_final_price).subtract(BigDecimal(good.coupon_price)).setScale(2, BigDecimal.ROUND_HALF_UP)
                                        good.final_price = if (couponFinalPrice > BigDecimal.ZERO) couponFinalPrice.toString() else "0"
                                        good.original_price = good.zk_final_price
                                    } else {
                                        good.final_price = good.zk_final_price
                                        good.original_price = good.reserve_price
                                    }

                                    val commission = BigDecimal(good.final_price)
                                            .multiply(BigDecimal(good.commission_rate))
                                            .multiply(RETURN_RATIO.toBigDecimal())
                                            .divide(BigDecimal(10000))

                                    val vipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val vipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    good.vip_commission = vipBuyCommission.add(vipShareCommission)
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()

                                    good.svip_commission = svipBuyCommission.add(svipShareCommission)
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()

                                    if (good.small_images != null &&
                                            good.small_images!!.toString() != "" &&
                                            good.small_images!!.toString() != "[]") {
                                        var array = good.small_images!!.toString()
                                        array = array.substring(8, array.length - 1)
                                        if (!array.contains(",")) {
                                            good.images.add(array)
                                        } else {
                                            val images = array.substring(1, array.length - 1).split(",")
                                            for (image in images) good.images.add(image)
                                        }
                                    }
                                }
                                when (item.cate) {
                                    "8" -> selectedGoods = item
                                }
                            }
                            it.data?.part2 = part2
                            it.data?.bannerTop?.images = images2
                            it.data?.types = types
                            it.data?.part4 = part4
                            it.data?.part5 = part5
                            it.data?.bannerBot?.images = images5
                            if (selectedGoods != null)
                                it.data?.selectedGoods = selectedGoods
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 获取淘宝客选品库商品
     */
    fun getGroupGoods(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<GroupGoodBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getGroupGoods(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data?.list!!.results.uatm_tbk_item.isNotEmpty()) {
                                val commissionRatio=DataUtils().getCommissionRatio()
                                val list = mutableListOf<TaobaoGoodBean>()
                                for (good in it.data?.list!!.results.uatm_tbk_item) {
                                    good.commission_rate = good.tk_rate
                                    good.coupon_share_url = good.coupon_click_url
                                    good.url = good.click_url
                                    if (good.coupon_info != "") {
                                        good.has_coupon = true
                                        val start = good.coupon_info.indexOf("减")
                                        val str = good.coupon_info.substring(start + 1)
                                        val end = str.indexOf("元")
                                        good.coupon_price = str.substring(0, end)
                                        val couponFinalPrice = BigDecimal(good.zk_final_price).subtract(BigDecimal(good.coupon_price)).setScale(2, BigDecimal.ROUND_HALF_UP)
                                        good.final_price = if (couponFinalPrice > BigDecimal.ZERO) couponFinalPrice.toString() else "0"
                                        good.original_price = good.zk_final_price
                                    } else {
                                        good.final_price = good.zk_final_price
                                        good.original_price = good.reserve_price
                                    }
                                    val commission = BigDecimal(good.final_price)
                                            .multiply(BigDecimal(good.commission_rate))
                                            .multiply(RETURN_RATIO.toBigDecimal())
                                            .divide(BigDecimal(10000))

                                    val vipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val vipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    good.vip_commission = vipBuyCommission.add(vipShareCommission)
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()

                                    good.svip_commission = svipBuyCommission.add(svipShareCommission)
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()

                                    if (good.small_images != null &&
                                            good.small_images!!.toString() != "" &&
                                            good.small_images!!.toString() != "[]") {
                                        var array = good.small_images!!.toString()
                                        array = array.substring(8, array.length - 1)
                                        if (!array.contains(",")) {
                                            good.images.add(array)
                                        } else {
                                            val images = array.substring(1, array.length - 1).split(",")
                                            for (image in images) good.images.add(image)
                                        }
                                    }

                                    list.add(good)
                                }
                                it.data!!.list.results.uatm_tbk_item = list
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 获取后台设置分佣比例
     */
    fun getEarnData(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<EarnDataBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getEarnData(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 一级分类
     */
    fun getPrimarySorts(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<PrimarySortBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getPrimarySorts(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 二级分类
     */
    fun getSecondarySorts(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<SecondarySortBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getSecondarySorts(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 通用物料搜索
     */
    fun optionalSearch(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<OptionalGoodBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.optionalSearch(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data?.list!!.result_list.map_data.isNotEmpty()) {
                                val commissionRatio=DataUtils().getCommissionRatio()
                                for (good in it.data?.list!!.result_list.map_data) {
                                    good.coupon_share_url = "https:${good.coupon_share_url}"
                                    good.url = "https:${good.url}"
                                    if (good.coupon_info != "") {
                                        good.has_coupon = true
                                        val start = good.coupon_info.indexOf("减")
                                        val str = good.coupon_info.substring(start + 1)
                                        val end = str.indexOf("元")
                                        good.coupon_price = str.substring(0, end)
                                        val couponFinalPrice = BigDecimal(good.zk_final_price).subtract(BigDecimal(good.coupon_price)).setScale(2, BigDecimal.ROUND_HALF_UP)
                                        good.final_price = if (couponFinalPrice > BigDecimal.ZERO) couponFinalPrice.toString() else "0"
                                        good.original_price = good.zk_final_price
                                    } else {
                                        good.final_price = good.zk_final_price
                                        good.original_price = good.reserve_price
                                    }
                                    val commission = BigDecimal(good.final_price)
                                            .multiply(BigDecimal(good.commission_rate))
                                            .multiply(RETURN_RATIO.toBigDecimal())
                                            .divide(BigDecimal(1000000))

                                    val vipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val vipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    good.vip_commission = vipBuyCommission.add(vipShareCommission)
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()

                                    good.svip_commission = svipBuyCommission.add(svipShareCommission)
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()

                                    if (good.small_images != null &&
                                            good.small_images!!.toString() != "" &&
                                            good.small_images!!.toString() != "[]") {
                                        var array = good.small_images!!.toString()
                                        array = array.substring(8, array.length - 1)
                                        if (!array.contains(",")) {
                                            good.images.add(array)
                                        } else {
                                            val images = array.substring(1, array.length - 1).split(",")
                                            for (image in images) good.images.add(image)
                                        }
                                    }
                                }
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 店铺单品搜索
     */
    fun shopOptionalSearch(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<OptionalGoodBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.optionalSearch(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data?.list!!.result_list.map_data.isNotEmpty()) {
                                val commissionRatio=DataUtils().getCommissionRatio()
                                val good = it.data?.list!!.result_list.map_data[0]
                                good.coupon_share_url = "https:${good.coupon_share_url}"
                                good.url = "https:${good.url}"
                                if (good.coupon_info != "") {
                                    good.has_coupon = true
                                    val start = good.coupon_info.indexOf("减")
                                    val str = good.coupon_info.substring(start + 1)
                                    val end = str.indexOf("元")
                                    good.coupon_price = str.substring(0, end)
                                    val couponFinalPrice = BigDecimal(good.zk_final_price).subtract(BigDecimal(good.coupon_price)).setScale(2, BigDecimal.ROUND_HALF_UP)
                                    good.final_price = if (couponFinalPrice > BigDecimal.ZERO) couponFinalPrice.toString() else "0"
                                    good.original_price = good.zk_final_price
                                } else {
                                    good.final_price = good.zk_final_price
                                    good.original_price = good.reserve_price
                                }
                                val commission = BigDecimal(good.final_price)
                                        .multiply(BigDecimal(good.commission_rate))
                                        .multiply(RETURN_RATIO.toBigDecimal())
                                        .divide(BigDecimal(1000000))

                                val vipBuyCommission = commission
                                        .multiply(commissionRatio.toBigDecimal())

                                val vipShareCommission = commission
                                        .multiply(commissionRatio.toBigDecimal())

                                val svipBuyCommission = commission
                                        .multiply(commissionRatio.toBigDecimal())

                                val svipShareCommission = commission
                                        .multiply(commissionRatio.toBigDecimal())

                                good.vip_commission = vipBuyCommission.add(vipShareCommission)
                                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                                        .toString()

                                good.svip_commission = svipBuyCommission.add(svipShareCommission)
                                        .setScale(2, BigDecimal.ROUND_HALF_UP)
                                        .toString()

                                if (good.small_images != null &&
                                        good.small_images!!.toString() != "" &&
                                        good.small_images!!.toString() != "[]") {
                                    var array = good.small_images!!.toString()
                                    array = array.substring(8, array.length - 1)
                                    if (!array.contains(",")) {
                                        good.images.add(array)
                                    } else {
                                        val images = array.substring(1, array.length - 1).split(",")
                                        for (image in images) good.images.add(image)
                                    }
                                }

                                it.data!!.couponGood = good
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 淘口令
     */
    fun getTaoKouLing(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<String>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getTKLing(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 分享信息写入后台接口
     */
    fun saveShareItemInfo(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<String>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.newSaveShareItemInfo(
                        RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null) {
                                it.data =it.data
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 每日爆款和宣传素材接口
     * 义乌接口
     */
    fun getCircleShare(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<ShareCircleBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getCircleShare(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data!!.list.isNotEmpty()) {
                                //Log.e("eeee","---->集合不为空")
                                val commissionRatio=DataUtils().getCommissionRatio()
                                for (item in it.data!!.list) {
                                    item.title = item.title.replace("&", "")
                                            .replace("lt;", "<")
                                            .replace("amp", "")
                                            .replace("gt;", ">")
                                            .replace("quot;", "\"")
                                            .replace(";", "")
                                            .replace("nbsp", "")
                                    var document = Jsoup.parse(item.title ?: "")
                                    val ps = document.getElementsByTag("p")
                                    val sb = StringBuilder()
                                    for (i in 0 until ps.size) {
                                        if (ps[i].text() != "") {
                                            if (ps[i].text().endsWith("查看详情"))
                                                sb.append(ps[i].text().replace("查看详情", "")).append("<br>")
                                            else
                                                sb.append(ps[i].text()).append("<br>")
                                        }
                                    }
                                    if (sb.length > 4)
                                        item.title = sb.substring(0, sb.length - 4)
                                    item.content = item.content.replace("&", "")
                                            .replace("lt;", "<")
                                            .replace("amp", "")
                                            .replace("gt;", ">")
                                            .replace("quot;", "\"")
                                            .replace(";", "")
                                    document = Jsoup.parse(item.content ?: "")
                                    val imgs = document.getElementsByTag("img")
                                    val images = arrayListOf<String>()
                                    for (img in imgs)
                                        images.add(img.attr("src"))
                                    item.images = images
                                    if (item.goodsinfo != "") {
                                        val json = item.goodsinfo
                                                .replace("&amp;", "&")
                                                .replace("&quot;", "\"")
                                                .replace("quot;", "\"")
                                        if (!json.contains("\"info_dxjh\"")) {
                                            item.goodBean = Gson().fromJson(json, TaobaoGoodBean::class.java)
                                        } else {
                                            if (json.contains("\"info_dxjh\":\"{}\"")) {
                                                item.goodBean = Gson().fromJson(json, TaobaoGoodBean::class.java)
                                            } else {
                                                val s = json.indexOf("\"info_dxjh\"")
                                                val other = json.substring(s)
                                                val index = other.indexOf(",")
                                                item.goodBean = Gson().fromJson(
                                                        json.substring(0, s) + other.substring(index + 1),
                                                        TaobaoGoodBean::class.java)
                                            }
                                        }

                                        item.goodBean.coupon_share_url = "https:${item.goodBean.coupon_share_url}"
                                        if (item.goodBean.coupon_id != "")
                                            item.goodBean.coupon_share_url_new = "https://uland.taobao.com/coupon/edetail?activityId=${item.goodBean.coupon_id}&itemId=${item.goodBean.num_iid}&pid=${Contacts.ALIMAMA_PID}${AppUtils.getString(Contacts.ADZONE_ID, "")}"
                                        item.goodBean.url = "https:${item.goodBean.url}"
                                        if (item.goodBean.coupon_info != "") {
                                            item.goodBean.has_coupon = true
                                            val start = item.goodBean.coupon_info.indexOf("减")
                                            val str = item.goodBean.coupon_info.substring(start + 1)
                                            val end = str.indexOf("元")
                                            item.goodBean.coupon_price = str.substring(0, end)
                                            val couponFinalPrice = BigDecimal(item.goodBean.zk_final_price).subtract(BigDecimal(item.goodBean.coupon_price)).setScale(2, BigDecimal.ROUND_HALF_UP)
                                            item.goodBean.final_price = if (couponFinalPrice > BigDecimal.ZERO) couponFinalPrice.toString() else "0"
                                            item.goodBean.original_price = item.goodBean.zk_final_price ?: ""
                                        } else {
                                            item.goodBean.final_price = item.goodBean.zk_final_price ?: ""
                                            item.goodBean.original_price = item.goodBean.reserve_price ?: ""
                                        }
                                        val commission = BigDecimal(item.goodBean.final_price)
                                                .multiply(BigDecimal(item.goodBean.commission_rate))
                                                .multiply(RETURN_RATIO.toBigDecimal())
                                                .divide(BigDecimal(10000))

                                        val vipBuyCommission = commission
                                                .multiply(commissionRatio.toBigDecimal())

                                        val svipBuyCommission = commission
                                                .multiply(commissionRatio.toBigDecimal())

                                        item.goodBean.vip_commission = vipBuyCommission
                                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                                                .toString()

                                        item.goodBean.svip_commission = svipBuyCommission
                                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                                                .toString()

                                        if (item.goodBean.small_images != null &&
                                                item.goodBean.small_images!!.toString() != "" &&
                                                item.goodBean.small_images!!.toString() != "[]") {
                                            var array = item.goodBean.small_images!!.toString()
                                            array = array.substring(8, array.length - 1)
                                            if (!array.contains(",")) {
                                                item.goodBean.images.add(array)
                                            } else {
                                                val imagess = array.substring(1, array.length - 1).split(",")
                                                for (image in imagess) item.goodBean.images.add(image)
                                            }
                                        }
                                    }
                                }
                            }else{
                                //Log.e("eeee","---->集合为空")
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 每日爆款和宣传素材分享回调
     */
    fun circleShareSuccess(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.circleShareSuccess(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 密码登录
     */
    fun passwordLogin(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<TokenBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.passwordLogin(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 验证码登录
     */
    fun checkCodeLogin(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<TokenBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.checkCodeLogin(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 验证码登录
     */
    fun checkCodeLoginSend(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.checkCodeLoginSend(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 注册
     */
    fun userRegister(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<TokenBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.userRegister(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 注册发送验证码
     */
    fun userRegisterCheckCode(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.userRegisterCheckCode(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 退出登录
     */
    fun userLogOut(map: Map<String, String>): LiveData<ViewDataBean<ResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.userLogOut(mapOf(Pair("param", map["param"]!!)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }
    /**
     * 微信登录
     */
    fun wxLogin(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<NewBindPhoneBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.wxLogin(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }
    /**
     * 绑定手机号
     */
    fun bindPhone(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<NewBindPhoneBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.bindPhone(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }
    /**
     * 绑定手机号
     */
    fun wxRegister(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<NewBindPhoneBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.wxRegister(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }
    /**
     * 用户签到
     */
    fun userSign(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.userSign(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 用户签到信息
     */
    fun getUserSignInfo(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<SignInfoBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getUserSignInfo(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 个人中心
     */
    fun userCenter(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<UserCenterBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.userCenter(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            it.data!!.balance = BigDecimal(it.data!!.balance)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.todayForecast = BigDecimal(it.data!!.todayForecast)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.sumForecast = BigDecimal(it.data!!.sumForecast)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 用户团队信息
     */
    fun getUserTeamInfo(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<UserTeamInfoBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getUserTeamInfo(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 用户团队列表
     */
    fun getUserTeamList(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<UserTeamMemberBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getUserTeamList(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 获得收益基础数据
     */
    fun getUserProfit(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<UserProfitBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getUserProfit(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            it.data!!.balance = BigDecimal(it.data!!.balance)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.lastMonthForecast = BigDecimal(it.data!!.lastMonthForecast)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.lastMonthSettlement = BigDecimal(it.data!!.lastMonthSettlement)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.sumSettlement = BigDecimal(it.data!!.sumSettlement)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.sumWithdrawDeposit = BigDecimal(it.data!!.sumWithdrawDeposit)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.thisMonthForecast = BigDecimal(
                                    if (it.data!!.thisMonthForecast == null) "0" else it.data!!.thisMonthForecast!!)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.todayForecast = BigDecimal(it.data!!.todayForecast)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.todayRests = BigDecimal(it.data!!.todayRests)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.yesterdayForecast = BigDecimal(it.data!!.yesterdayForecast)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it.data!!.yesterdayRests = BigDecimal(it.data!!.yesterdayRests)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 收益记录
     */
    fun getProfitRecords(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<ProfitRecordsBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getProfitRecords(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null && it.data!!.records != null)
                                for (item in it.data!!.records!!) {
                                    item.credit2 = BigDecimal(item.credit2)
                                            .divide(BigDecimal(1))
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()
                                }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 提现记录
     */
    fun getWithdrawRecords(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<WithdrawRecordsBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getWithdrawRecords(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null && it.data!!.records != null)
                                for (item in it.data!!.records!!) {
                                    item.money = BigDecimal(item.money)
                                            .divide(BigDecimal(1))
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()
                                }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 用户支付宝信息
     */
    fun getAlipayInfo(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<AlipayInfoBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getAlipayInfo(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            it.data!!.balance = BigDecimal(it.data!!.balance)
                                    .divide(BigDecimal(1))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 发送验证码
     */
    fun sendCheckCode(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.sendCheckCode(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 用户绑定支付宝
     */
    fun bindAlipay(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.bindAlipay(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 支付宝提现
     */
    fun addWithdrawApply(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.addWithdrawApply(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 券金记录
     */
    fun getCouponKingRecordPage(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<CouponMoneyRecordBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getCouponKingRecordPage(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 券力记录
     */
    fun getCouponForceRecordPage(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<CouponMoneyRecordBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getCouponForceRecordPage(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 券金
     */
    fun getCouponKing(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<CouponMoneyBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getCouponKing(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 领取券金
     */
    fun addCouponKing(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.addCouponKing(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 更改用户信息
     */
    fun updateUser(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.updateUser(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * base64图片上传
     */
    fun uploadPicBase64(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.uploadPicBase64(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), map["base64String"]!!))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 用户是否存在
     */
    fun getUserIsCorrect(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getUserIsCorrect(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 修改密码
     */
    fun updatePassword(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.updatePassword(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 获取用户标签
     */
    fun getAllTag(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<List<UserTagBean>>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getAllTag(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 保存用户标签
     */
    fun saveTag(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.saveTag(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 常见问题
     */
    fun getCommonProblems(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<List<CommonProblemBean>>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getCommonProblems(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 多图上传
     */
    fun uploadMultiPics(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        val list = map["files"]!!.split(",")
        val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
        for (item in list) {
            if (item != "") {
                val file = File(item)
                builder.addFormDataPart("files", file.name, RequestBody.create(MediaType.parse("multipart/form-data"), file))
            }
        }
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.uploadMultiPics(builder.build())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 问题反馈
     */
    fun addFeedback(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.addFeedback(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 收藏列表
     */
    fun getCollectList(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<CollectListBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getCollectList(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null && it.data!!.records.isNotEmpty()) {
                                val commissionRatio=DataUtils().getCommissionRatio()
                                for (item in it.data!!.records) {
                                    val good = TaobaoGoodBean()
                                    good.title = item.title
                                    good.coupon_info = item.couponInfo
                                    good.zk_final_price = item.zkFinalPrice
                                    good.reserve_price = item.reservePrice
                                    good.num_iid = item.numIid
                                    good.commission_rate = item.commissionRate
                                    good.url = item.clickUrl
                                    good.coupon_remain_count = item.couponRemainCount
                                    good.item_url = item.itemUrl
                                    good.pict_url = item.pictUrl
                                    good.small_images = item.smallImages
                                    good.volume = item.volume
                                    good.collectId = item.id
                                    good.shop_title = ""
                                    good.coupon_start_time=item.couponStartTime
                                    good.coupon_end_time=item.couponEndTime
                                    good.goodsSource=when(item.platformType){
                                        "0"->{
                                            good.userType= R.drawable.goods_tb
                                            "淘宝"
                                        }
                                        "1"->{
                                            good.userType= R.drawable.goods_tm
                                            "天猫"
                                        }
                                        "3"->{
                                            good.userType= R.drawable.goods_pdd
                                            "拼多多"
                                        }
                                        "4"->{
                                            good.userType= R.drawable.goods_jd
                                            "京东"
                                        }
                                        else->{
                                            ""
                                        }
                                    }
                                    good.goodsSource1="好单库"
                                    good.item_id=item.numIid
                                    good.has_coupon = good.coupon_info != ""
                                    good.coupon_price =item.couponInfo
                                    good.final_price = item.zkFinalPrice
                                    good.original_price = item.reservePrice
                                    //good.original_price=item.reservePrice
                                    val commission = BigDecimal(good.final_price)
                                            .multiply(BigDecimal(good.commission_rate))
                                            .multiply(RETURN_RATIO.toBigDecimal())
                                            .divide(BigDecimal(100))

                                    val vipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val vipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    good.vip_commission = vipBuyCommission
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()

                                    good.svip_commission = svipBuyCommission
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()
                                    if (good.small_images != null &&
                                            good.small_images!!.toString() != "" &&
                                            good.small_images!!.toString() != "[]") {
                                        val array = good.small_images!!.toString()
                                        /*try {
                                            var imagurls=good.small_images!!.toString().replace("\\\\\\","")
                                            val goodsBannerListBean=Gson().fromJson<GoodsBannerListBean>(good.small_images!!.toString(),GoodsBannerListBean::class.java)
                                            good.images.addAll(goodsBannerListBean.string!!)
                                        }catch (e:Exception){
                                            Log.e("soucang",e.toString())
                                        }*/
                                        //array=array.replace("{string","").replace("}","")
                                        //array=array.substring(0,array.length)
                                        if (!array.contains(",")) {
                                            good.images.add(array)
                                        } else {
                                            val imagess = array.split(",")
                                            for (image in imagess) good.images.add(image)
                                        }
                                    }

                                    it.data!!.recordss.add(good)
                                }
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 添加收藏
     */
    fun addCollect(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.addCollect(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 订单
     */
    fun getOrderList(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<TaobaoOrderBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getOrderList(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 商品是否收藏
     */
    fun isGoodCollect(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.isGoodCollect(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 商品是否收藏
     */
    fun cancelCollect(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.cancelCollect(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 本地生活首页
     */
    fun getLifeHomePage(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<LifeHomePageBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getLifeHomePage(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            val imagesTop = arrayListOf<String>()
                            val imagesBot = arrayListOf<String>()
                            if (it.data != null && it.data!!.topBanner.isNotEmpty()) {
                                for (item in it.data!!.topBanner) {
                                    imagesTop.add(Contacts.REMOTE_IMAGE_URL + item.value)
                                }
                                it.data?.bannerTop?.images = imagesTop
                            }
                            if (it.data != null && it.data!!.belowBanner.isNotEmpty()) {
                                for (item in it.data!!.belowBanner) {
                                    imagesBot.add(Contacts.REMOTE_IMAGE_URL + item.value)
                                }
                                it.data?.bannerBot?.images = imagesBot
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 本地生活分类搜索
     */
    fun getLifeShopPage(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<LifeShopPageBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getLifeShopPage(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null && it.data!!.records.isNotEmpty()) {
                                for (item in it.data!!.records) {
                                    if (item.images != null) {
                                        item.listImages = item.images!!.split(",").toMutableList()
                                    }
                                    if (item.cards!!.isNotEmpty()) {
                                        val size = if (item.cards!!.size < 2) item.cards!!.size else 2
                                        for (i in 0 until size) {
                                            if (i == 0) {
                                                item.couponOneContent = getCouponContent(item.cards!![0])
                                            } else if (i == 1) {
                                                item.couponTwoContent = getCouponContent(item.cards!![1])
                                            }
                                        }
                                    }
                                    item.distance = calculateDistance(item.longitude!!, item.latitude!!)
                                }
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    private fun calculateDistance(longitude: String, latitude: String): String {
        return if (longitude != "" && latitude != "") {
            val lat1 = rad(AppUtils.getString("Latitude", Contacts.HZ_CENTER_LATITUDE))
            val lat2 = rad(latitude)
            val lon1 = rad(AppUtils.getString("Longitude", Contacts.HZ_CENTER_LONGITUDE))
            val lon2 = rad(longitude)
            val a = lat1 - lat2
            val b = lon1 - lon2
            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2.0) + (Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2.0))))
            s *= Contacts.EARTH_RADIUS
            s = (Math.round(s * 10000) / 10000).toDouble()
            if (s > 1000) {
                "${BigDecimal(s / 1000).setScale(1, BigDecimal.ROUND_HALF_UP)}公里"
            } else {
                "${s}米"
            }
        } else "0米"
    }

    private fun rad(d: String): Double {
        return d.toDouble() * Math.PI / 180.0
    }

    private fun getCouponContent(bean: LifeShopPageBean.CardsBean): String {
        return if (bean.cardType == "CASH") {
            "满${bean.leastMoneyToUse}减${bean.reduceMoney}"
        } else {
            "${BigDecimal(100).subtract(BigDecimal(bean.discount)).setScale(1, BigDecimal.ROUND_HALF_UP)}折"
        }
    }

    /**
     * 本地生活热搜
     */
    fun getLifeHotKeyword(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<List<String>>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getLifeHotKeyword(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 本地生活店铺详情
     */
    fun getLifeShopInfo(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<LifeShopPageBean.RecordsBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getLifeShopInfo(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null) {
                                if (it.data!!.images != null) {
                                    it.data!!.listImages = it.data!!.images!!.split(",").toMutableList()
                                }
                                for (i in 0 until it.data!!.listImages.size) {
                                    var image=it.data!!.listImages[i]
                                    if (image.contains("q11")){
                                        image= "http:$image"
                                    }else{
                                        image=APP_LIFE_IMGURL+image
                                    }
                                    it.data!!.listImages[i] = image
                                }
//                                2018-12-10 00:00:00
                                val start = if (it.data!!.openingTime != null && it.data!!.openingTime!!.length == 19)
                                    it.data!!.openingTime!!.substring(11, 16) else ""
                                val end = if (it.data!!.closingTime != null && it.data!!.closingTime!!.length == 19)
                                    it.data!!.closingTime!!.substring(11, 16) else ""
                                it.data!!.shop.openTime = String.format("%s-%s", start, end)
                                it.data!!.shop.people = it.data!!.creator?:""
                                it.data!!.shop.phone =it.data!!.phone?:""
                                it.data!!.shop.address = it.data!!.address?:""
                                it.data!!.shop.telephone = if (it.data!!.telephone != null) it.data!!.telephone?:"" else ""

                                it.data!!.info.name = it.data!!.shopName?:""
                                it.data!!.info.info = if (it.data!!.remark != null) it.data!!.remark?:"" else ""
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 本地生活优惠券详情
     */
    fun getLifeCardInfo(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<LifeShopPageBean.CardsBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getLifeCardInfo(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 支付结果页面 新卡券
     */
    fun getLifeNewCard(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<LifeShopPageBean.CardsBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getLifeNewCard(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null) {
                                it.data!!.content = getNewCouponContent(it.data!!)
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    private fun getNewCouponContent(bean: LifeShopPageBean.CardsBean): String {
        return if (bean.cardType == "CASH") {
            "￥${bean.reduceMoney}"
        } else {
            "${BigDecimal(100).subtract(BigDecimal(bean.discount)).setScale(1, BigDecimal.ROUND_HALF_UP)}折"
        }
    }

    /**
     * 商品热搜
     */
    fun getHotKeyword(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<List<String>>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getHotKeyword(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 个人中心 推荐商品
     */
    fun getRecommendPage(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<UserCenterGoodBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getRecommendPage(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null && it.data!!.records.isNotEmpty()) {
                                for (item in it.data!!.records) {
                                    it.data!!.recordss.add(AppUtils.parseGood(item))
                                }
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 计算金额
     */
    fun payMoneyCalculate(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<PayMoneyBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.payMoneyCalculate(
                        RequestBody.create(MediaType.parse("application/json; charset=utf-8"), Gson().toJson(map)))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 首页淘宝二级页
     */
    fun getTaobaoTablePage(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<TaobaoTablePageBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getTaobaoTablePage(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .map {
                            if (it.data != null && it.data!!.records.isNotEmpty()) {
                                for (good in it.data!!.records) {
                                    it.data!!.recordss.add(AppUtils.parseGood1(good))
                                }
                            }
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 注册通知
     */
    fun registerInform(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<Any>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.registerInform(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }

    /**
     * 获取首页个分类页面的基本数据
     */
    fun getHomeBase(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<HomeBaseBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getHomeBase(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }
    /**
     * 获取首页分类商品数据
     */
    fun getFavoritesGoods(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<HomeChiocenGoodsBean>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getFavoritesItemPage(map)
                        .subscribeOn(Schedulers.io())
                        .map {
                            if (it.data != null && it.data!!.records!!.isNotEmpty()) {
                                val commissionRatio=DataUtils().getCommissionRatio()
                                val df = DecimalFormat("#0.00")
                                it.data!!.recordss= arrayListOf()
                                for (item in it.data!!.records!!) {
                                    val good = TaobaoGoodBean()
                                    good.title = item!!.title?:""
                                    good.coupon_info = item.couponInfo?:""
                                    good.zk_final_price = item.zkFinalPrice?:""
                                    good.reserve_price = item.reservePrice?:""
                                    good.num_iid = item.numIid.toString()
                                    good.commission_rate = item.tkRate?:""
                                    good.url = item.clickUrl?:""
                                    good.coupon_remain_count = item.couponRemainCount?:"0"
                                    good.item_url = item.itemUrl?:""
                                    good.pict_url = item.pictUrl?:""
                                    good.small_images = item.smallImages
                                    when(item.userType){
                                        0->{good.userType= R.drawable.goods_tb}
                                        1->{good.userType= R.drawable.goods_tm}
                                    }
                                    good.volume =if (item.volume!!>10000){
                                        "月销"+df.format(item.volume!!/10000)+"万"
                                    }else{
                                        "月销"+item.volume!!
                                    }
                                    good.collectId = ""
                                    good.shop_title = item.shopTitle?:""

                                    if (good.coupon_info.isNotEmpty()) {
                                        good.has_coupon = true
                                        val start = good.coupon_info.indexOf("减")
                                        val str = good.coupon_info.substring(start + 1)
                                        val end = str.indexOf("元")
                                        good.coupon_price = str.substring(0, end)
                                        val couponFinalPrice = BigDecimal(good.zk_final_price).subtract(BigDecimal(good.coupon_price)).setScale(2, BigDecimal.ROUND_HALF_UP)
                                        good.final_price = if (couponFinalPrice > BigDecimal.ZERO) couponFinalPrice.toString() else "0"
                                        good.original_price = good.zk_final_price
                                    } else {
                                        good.final_price = good.zk_final_price
                                        good.original_price = good.reserve_price
                                    }
                                    val commission = BigDecimal(good.final_price)
                                            .multiply(BigDecimal(good.commission_rate))
                                            .multiply(RETURN_RATIO.toBigDecimal())
                                            .divide(BigDecimal(10000))

                                    val vipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val vipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipBuyCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    val svipShareCommission = commission
                                            .multiply(commissionRatio.toBigDecimal())

                                    good.vip_commission = vipBuyCommission.add(vipShareCommission)
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()

                                    good.svip_commission = svipBuyCommission.add(svipShareCommission)
                                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                                            .toString()
                                    if (good.small_images != null &&
                                            good.small_images!!.toString() != "" &&
                                            good.small_images!!.toString() != "[]") {
                                        var array = good.small_images!!.toString()
                                        array=array.replace("{string=","").replace("}","")
                                        array=array.substring(0,array.length)
                                        if (!array.contains(",")) {
                                            good.images.add(array)
                                        } else {
                                            val imagess = array.substring(1, array.length - 1).split(",")
                                            for (image in imagess) good.images.add(image)
                                        }
                                    }
                                    it.data!!.recordss.add(good)
                            }}
                            it
                        }
                        .observeOn(AndroidSchedulers.mainThread()))
    }
    /**
     * 获取首页广播消息
     */
    fun getBroadcast(map: Map<String, String>): LiveData<ViewDataBean<RemoteResultBean<List<HomeBroadcastBean>>>> {
        return LiveDataObservableAdapter.fromObservableViewData(
                RetrofitWorker.retrofitWorker.getBroadcast(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()))
    }
}